﻿using System;
using System.IO;
using System.Management;

namespace Com.Lancetinc.Evs.Helpers
{
    public static class AuthorizationHelper
    {
        public static string GetCpuId()
        {
            using (var mbs = new ManagementObjectSearcher("select UUID from Win32_ComputerSystemProduct"))
            {
                var moList = mbs.Get();
                foreach (ManagementObject mo in moList)
                {
                    return mo["UUID"].ToString();
                }
                return string.Empty;
            }
        }

        public static string GetLicenseCode(string licenseCodePath = null)
        {
            if (string.IsNullOrEmpty(licenseCodePath))
            {
                licenseCodePath = GetLicenseCodeDefaultPath();
            }
            if (File.Exists(licenseCodePath))
            {
                return File.ReadAllText(licenseCodePath);
            }
            return string.Empty;
        }

        private static string GetLicenseCodeDefaultPath()
        {
            string licenseCodePath;
            var path = AppDomain.CurrentDomain.BaseDirectory;
            licenseCodePath = Path.Combine(path, "license_code.dat");
            return licenseCodePath;
        }

        public static bool CanBootstrap(string licenseCodePath = null)
        {
            return true;
            var doNotCheckCpuId = "a=0".Equals(AppConfigHelper.GetFirstConfigLine("a="));
            if (doNotCheckCpuId)
                return true;

            var finalCode = Md5Utils.Encrypt(GetCpuId());
            return finalCode.Equals(GetLicenseCode(licenseCodePath));
        }

        public static void SaveLicenseCodeFile(string licenseCodePath)
        {
            return;
            var finalPath = GetLicenseCodeDefaultPath();
            if (finalPath.Equals(licenseCodePath))
            {
                return;
            }
            if (File.Exists(finalPath))
            {
                File.Delete(finalPath);
            }
            File.Copy(licenseCodePath, finalPath);
        }
    }
}
